package com.sheepych.water_clock;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author sheepych
 */
@Slf4j
@Service
public class SendHealthMsgService {
    private static final String KEY = "e5e256f0-9d58-4c31-9df0-9faa9547cd88";
    private static final String URL = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=";
    private static final String START_TIME = "09:00";
    private static final String END_TIME = "21:00";
    private static final String REMINDER_MESSAGE = """
                ** 健康提醒 ** \s
               > 🧍 起身活动：走动 / 伸展 1～5 分钟 \s
               > 👀 眼睛休息：远眺 20 秒 \s
               > 🪑 坐姿检查：腰背挺直，眼平屏幕 \s
               > 🧘 深呼吸几次：放松颈肩，缓解紧张 \s
            """;


    public void sendMsg() {
        // Constants
        try {
            String nowTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("HH:mm"));
            if (!isWithinTimeRange(nowTime)) {
                //打印提醒
                log.info("当前时间不在提醒范围内【{}-{}】，跳过提醒", START_TIME, END_TIME);
                return;
            }

            Map<String, Object> paramMap = new HashMap<>(16);
            paramMap.put("msgtype", "markdown");
            Map<String, String> content = new HashMap<>(16);
            content.put("content", String.format(REMINDER_MESSAGE));
            paramMap.put("markdown", content);

            // Send request
            String url = URL + KEY;
            String body = JSONUtil.toJsonStr(paramMap);
            log.info("发送消息到企业微信: {}, 内容: {}", url, body);
            HttpUtil.post(url, body);
        } catch (Exception e) {
            log.error("发送消息到企业微信异常: {}", e.getMessage(), e);
        }
    }

    private boolean isWithinTimeRange(String currentTime) {
        try {
            LocalTime now = LocalTime.parse(currentTime);
            LocalTime start = LocalTime.parse(START_TIME);
            LocalTime end = LocalTime.parse(END_TIME);
            return !now.isBefore(start) && !now.isAfter(end);
        } catch (DateTimeParseException e) {
            log.error("时间比较出现异常: {}", e.getMessage(), e);
            return false;
        }
    }
}
